package com.example.flowershop.activity;

import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;

import com.example.flowershop.R;
import com.example.flowershop.adapter.StuffAdapter;
import com.example.flowershop.entity.Stuff;
import com.example.flowershop.sqlite.BusinessResult;
import com.example.flowershop.sqlite.TableStuff;

import java.util.List;

public class ManageActivity extends AppCompatActivity {

    private ImageView ivBack;

    private TextView tvAdd;

    private ListView lvStuff;

    private StuffAdapter stuffAdapter;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_manage);
        //绑定控件
        bindView();
        //初始化数据
        initData();
        //初始化控件
        initView();
    }

    private void initData() {
        BusinessResult<List<Stuff>> result = TableStuff.selectAll();
        stuffAdapter = new StuffAdapter(this, R.layout.item_stuff, result.getData());
    }

    private void bindView() {
        ivBack = findViewById(R.id.iv_back);
        tvAdd = findViewById(R.id.tv_add);
        lvStuff = findViewById(R.id.lv_stuff);
    }

    @Override
    protected void onResume() {
        super.onResume();
        stuffAdapter.setData(TableStuff.selectAll().getData());
    }

    private void initView() {
        //点击返回
        ivBack.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                finish();
            }
        });
        //点击添加商品
        tvAdd.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                //跳转到添加商品页面
                Intent intent = new Intent(ManageActivity.this, StuffEditActivity.class);
                startActivity(intent);
            }
        });
        //设置适配器
        lvStuff.setAdapter(stuffAdapter);
        lvStuff.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                Stuff stuff = (Stuff) adapterView.getItemAtPosition(i);
                Intent intent = new Intent(ManageActivity.this, StuffEditActivity.class);
                intent.putExtra("stuff", stuff);
                startActivity(intent);
            }
        });
    }
}
